#include "Heap.h"

void AdjustUp(HeapNodeDataType* array, int n)
{
	assert(array);
	int child = n;
	while (child > 0)
	{
		int parent = (child - 1) / 2;
		if (array[child] > array[parent])
		{
			Swap(&array[child], &array[parent]);
			child = parent;
		}
		else
		{
			break;
		}
	}
}
void AdjustDown(HeapNodeDataType* array, int n, int size)
{
	assert(array);
	int parent = n;
	int child = n * 2 + 1;
	if (child + 1 < size && array[child] > array[child + 1])
	{
		child = n * 2 + 2;
	}

	while (child < size)
	{
		if (array[child] < array[parent])
		{
			Swap(&array[child], &array[parent]);
			parent = child;
			child = parent * 2 + 1;
			if (child + 1 < size && array[child] > array[child + 1])
			{
				child = parent * 2 + 2;
			}
		}
		else
		{
			break;
		}
	}
}
void HeapInit(Heap* php)
{
	assert(php);
	php->_a = NULL;
	php->_capacity = php->_size = 0;
}
void HeapDestory(Heap* php)
{
	assert(php);
	assert(php->_a);
	free(php->_a);
	php->_capacity = php->_size = 0;
}
void HeapPush(Heap* php, HeapNodeDataType data)
{
	assert(php);
	if (php->_capacity == php->_size)
	{
		int newCapacity = php->_capacity == 0 ? 4 : php->_capacity * 2;
		HeapNodeDataType* newArray = (HeapNodeDataType*)realloc(php->_a, sizeof(HeapNodeDataType) * newCapacity);
		php->_a = newArray;
		php->_capacity = newCapacity;
	}
	php->_a[php->_size] = data;
	int child = php->_size;
	php->_size++;
	AdjustUp(php->_a, child);
}
void HeapPop(Heap* php)
{
	assert(php);
	assert(php->_a);
	Swap(&php->_a[0], &php->_a[php->_size - 1]);
	php->_size--;
	AdjustDown(php->_a, 0, php->_size);
}
HeapNodeDataType HeapTop(Heap* php)
{
	assert(php);
	assert(php->_a);
	return php->_a[0];
}
int HeapSize(Heap* php)
{
	assert(php);
	return php->_size;
}
void Swap(HeapNodeDataType* a, HeapNodeDataType* b)
{
	HeapNodeDataType tmp = *b;
	*b = *a;
	*a = tmp;
}
bool HeapEmpty(Heap* php)
{
	return php->_size == 0;
	assert(php);
}
